<!--
 * @description: 地图显示
 * @fileName: index.vue
 * @author: ssr
 * @date: 2022-08-12 09:38:14
 * @version: V1.0.0
!-->
<template>
  <div id="cesium-container-situation" class="cesium-container">
  </div>
</template>

<script>
import * as Cesium from "cesium";
import { defineComponent, onBeforeUnmount, onActivated, onMounted, nextTick, ref } from "vue";
import { CustomViewer } from "@@/utils/CustomCesium/CustomCesium";
import { cesiumState } from "@/pinia/stores/cesium";
import { simulationState } from "@/pinia/stores/simulation";
export default defineComponent({
  props: {
    customViewer: {
      type: Object,
      default: () => null,
    },
  },
  emits: ["update:customViewer"],
  setup(props, { emit }) {
    const store = cesiumState();
    const simulaStore = simulationState()
    const isInitialized = ref(false);
    const viewerInstance = ref(null);

    // 销毁地图实例
    const destroyViewer = () => {
      if (viewerInstance.value) {
        try {
          const viewer = viewerInstance.value.viewer;
          if (viewer && !viewer.isDestroyed()) {
            viewer.entities.removeAll();
            viewer.dataSources.removeAll(true);
            viewer.destroy();
          }
          viewerInstance.value = null;
          store.setCustomViewer(null);
        } catch (e) {
          console.error('销毁地图实例失败:', e);
        }
      }
      isInitialized.value = false;
    };

    // 初始化地图
    const initMap = async () => {
      try {
        /// 设置初始化视框
        const extent = Cesium.Rectangle.fromDegrees(90, -20, 110, 90);
        Cesium.Camera.DEFAULT_VIEW_RECTANGLE = extent;

        // 确保容器存在
        const container = document.getElementById('cesium-container-situation');
        if (!container) {
          return;
        }

        // 如果已经存在viewer实例，先销毁
        destroyViewer();

        // 等待DOM更新
        await nextTick();

        const customViewer = new CustomViewer("cesium-container-situation");
        viewerInstance.value = customViewer;
        /// 实例化Map
        store.setCustomViewer(customViewer);

        // 等待下一帧确保DOM更新
        await nextTick();

        customViewer.viewer.camera.flyTo({
          destination: Cesium.Rectangle.fromDegrees(30, 0, 180, 50),
          duration: 0 // 立即定位，不使用动画
        });

        emit("update:customViewer", customViewer);
        isInitialized.value = true;
      } catch (error) {
        destroyViewer();
      }
    }

    // 首次挂载
    // onMounted(() => {
    //   initMap();
    // });

    // 从缓存激活
    onActivated(async () => {

      // 每次激活时都重新初始化，确保只有一个实例
      await initMap();
    });
    // 组件失活
    onDeactivated(() => {
      simulaStore.reAllStepsList()
      destroyViewer();

    });
    // 组件销毁
    onBeforeUnmount(() => {
      destroyViewer();
      simulaStore.reAllStepsList()
    });

    return {
      destroyViewer
    };
  },
});
</script>

<style scoped>
.cesium-container {
  width: 100%;
  height: 100%;
  position: relative;
}
</style>
